#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <unistd.h>
#include <time.h>
#include "dht.h"


struct sockaddr_in this_client_info;
struct sockaddr_in dht_node_info;

int this_node_port_num;

char root_node_ip[64];
int root_node_port;

int this_client_socket;
char send_data[1024],recv_data[1024];
int bytes_recieved;

int main(int argc, char *argv[]){
  	if (argc !=2) {
		
		printf("Usage: \n %s <dhtnode>\n", argv[0]);
		
	} else {
		
	  //	printf("This Node is\t: %i\n", this_node_port_num);
		
		char node_input[64];
		
		char *node_in;
		
		strncpy(node_input, argv[1], 64-1);
		
	    //char *node_input;
	    node_in = strtok(node_input, ":");

	    if(node_in)
	    {
			strncpy(root_node_ip, node_in, 64-1);
	    	printf("Root Node IP\t: %s\n", root_node_ip);
	    }
	    node_in = strtok(NULL, ":");

	    if(node_in) {
			root_node_port = atoi(node_in);
			printf("Root Node Port\t: %i\n", root_node_port);
		}

   
        char * s = malloc(3);
        memcpy(s, "6n|", 2);

	node_connect(root_node_ip,root_node_port, s);
	}

}


int node_connect(int dst_ip[64], int dst_port, char send_data[512]){
        //creating socket using TCP
  if ((this_client_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
    perror("Socket Error");
    exit(EXIT_FAILURE);
  }
  
  //dht_node_host = gethostbyname(dst_ip);
  
  this_client_info.sin_family = AF_INET; 
  inet_aton(dst_ip, &(this_client_info.sin_addr)); 
  this_client_info.sin_port = htons(dst_port);
  bzero(&(this_client_info.sin_zero), 8);
  printf("connected...\n");
  
  if (connect(this_client_socket, (struct sockaddr *)&this_client_info,
	      sizeof(struct sockaddr)) == -1)
    {
      perror("Connect Error\t");
      exit(1);
    }
    
    send(this_client_socket,send_data,strlen(send_data), 0);   
    close(this_client_socket);

    /*while(1)
    {
        
       bytes_recieved=recv(this_client_socket,recv_data,1024,0);
        recv_data[bytes_recieved] = '\0';
        
        if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0)
        {
            close(this_client_socket);
            break;
        }
        
        else
            printf("\nRecieved data = %s " , recv_data);
        
        printf("\nSEND (q or Q to quit) : ");
        fflush(stdout);
        //gets(send_data);
        
        if (strcmp(send_data , "q") != 0 && strcmp(send_data , "Q") != 0)
            send(this_client_socket,send_data,strlen(send_data), 0); 
        
        else
        {
            send(this_client_socket,send_data,strlen(send_data), 0);   
            close(this_client_socket);
            break;
        }
        
    }  */ 
    return 0;



	
}
